﻿/** Common escencials funcions */

var __currentDictionary;
var __processDictionary;
var __resizeDictionary;


$(document).ready(function () {
    var mobile = false,
	tooltipOnlyForDesktop = true,
	notifyActivatedSelector = 'button-active';

    if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) {
        mobile = true;
    }


    // Translate function for HTML templates
    Handlebars.registerHelper('L', function (text) {
        return translate(text);
    });

    // Format an date from database
    Handlebars.registerHelper('formatDate', function (text) {
        return formatDate(text);
    });



    // get the base URL (api URL)
    Handlebars.registerHelper('baseURL', function () {
        return __baseUrl;
    });

    // Return random number (used for skip cache)
    Handlebars.registerHelper('rand', function () {
        return Math.random() * 100;
    });


    Handlebars.registerHelper('inArray', function (value, array, options) {
        return jQuery.inArray(value, array) ? options.fn(this) : options.inverse(this);
    });

    Handlebars.registerHelper('if_even', function (conditional, options) {
        if ((conditional % 2) == 0) {
            return options.fn(this);
        } else {
            return options.inverse(this);
        }
    });

    Handlebars.registerHelper('ifCond', function (v1, operator, v2, options) {
        switch (operator) {
            case '==':
                return (v1 == v2) ? options.fn(this) : options.inverse(this);
                break;
            case '!=':
                return (v1 != v2) ? options.fn(this) : options.inverse(this);
                break;
            case '===':
                return (v1 === v2) ? options.fn(this) : options.inverse(this);
                break;
            case '<':
                return (v1 < v2) ? options.fn(this) : options.inverse(this);
                break;
            case '<=':
                return (v1 <= v2) ? options.fn(this) : options.inverse(this);
                break;
            case '>':
                return (v1 > v2) ? options.fn(this) : options.inverse(this);
                break;
            case '>=':
                return (v1 >= v2) ? options.fn(this) : options.inverse(this);
                break;
            default:
                return options.inverse(this)
                break;
        }
    });

    Handlebars.registerHelper('console', function (obj) {
        console.log(obj);
    });

    Handlebars.registerHelper('haveAccess', function (process, options) {
        if (haveAccess(process))
            return options.fn(process);
        else
            return "";
    });


    Handlebars.registerHelper('baseUrl', function (process, options) {
        return __baseUrl;
    });



    $(window).on("resize", function () {

        if (__resizeDictionary) {

            for (var key in __resizeDictionary) {

                setTimeout(__resizeDictionary[key], 200);
            }
        }


    });



    String.prototype.width = function (font) {
        var f = font || '13px arial',
            o = $('<div>' + this + '</div>')
                  .css({ 'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f })
                  .appendTo($('body')),
            w = o.width();

        o.remove();

        return w;
    }




});

// Toggle top-left loading icon
function toggleLoading(flag) {
    if (flag) {
        $("#logoLoadIcon").addClass("fa-spin");
        //$("#logoLoadName").removeClass("in");
    } else {
        $("#logoLoadIcon").removeClass("fa-spin");
        //$("#logoLoadName").addClass("in");
    }
}

// Clear Element Content
function clearContent($element, callback) {
    $element.find('.live-tile').each(function () {
        $element.liveTile("destroy", true);
    });
   
    $element.children().remove();
    (callback || null) && callback();
}
// Cambiar el titulo principal de la barra de navegacion que esta arriba
function changeTopNavTitle(title) {
    $("nav.navbar .navbar-center").text(translate(title));
}

// ensure only one resize event per class
function registerResizeEvents(key, callback) {

    if (!__resizeDictionary)
        __resizeDictionary = new Object();

    //if (!__resizeDictionary.hasOwnProperty("key")) {
        __resizeDictionary[key] = callback;
    //}
}

function removeResizeEvent(key) {

    if (__resizeDictionary && __resizeDictionary[key]) {
        __resizeDictionary[key] = null;
        delete __resizeDictionary[key];
    }
}



// call all function to setup html
function postRender(parent) {

    if (parent == undefined)
        parent = "body"

    iconValidation(parent);
    customSwitch(parent);
    icheck(parent);
    applyValidate(parent);
    scrollable(parent);
    select2(parent);
}

function iconValidation(parent) {
    /****  Form Validation with Icons  ****/
    if ($('.icon-validation').length && $.fn.parsley) {
        $('.icon-validation').each(function () {
            $(this).parsley({
                listeners: {
                    onFieldSuccess: function (elem, constraints) {
                        elem.prev().removeClass('fa-exclamation c-red').addClass('fa-check c-green');
                    },
                    onFieldError: function (elem, constraints) {
                        elem.prev().removeClass('fa-check c-green').addClass('fa-exclamation c-red');
                    }
                }
            });
        });
    }
}

function customSwitch(parent) {
    if ($('.switch').length && $.fn.bootstrapSwitch) {
        $('.switch').each(function () {
            var switch_size = $(this).data('size') ? $(this).data('size') : '';
            var switch_on_color = $(this).data('on-color') ? $(this).data('on-color') : 'primary';
            var switch_off_color = $(this).data('off-color') ? $(this).data('off-color') : 'primary';
            $(this).bootstrapSwitch('size', switch_size);
            $(this).bootstrapSwitch('onColor', switch_on_color);
            $(this).bootstrapSwitch('offColor', switch_off_color);
        });
    }
}

function select2(parent) {
    if ($(parent).find(".select2-me").length > 0) {

        $(parent).find('.select2-me').each(function () {
            var options = {};
            if ($(this).attr("data-nosearch") == "1") {
                options.minimumResultsForSearch = -1;
            }

            $(this).select2(options);

        });
    }

}


// add scrollable to elements
function scrollable(parent) {

    $(parent).find('.scrollable').each(function () {
        var $el = $(this);
        var height = parseInt($el.attr('data-height')),
        vis = ($el.attr("data-visible") == "true") ? true : false,
        start = ($el.attr("data-start") == "bottom") ? "bottom" : "top";
        var opt = {
            height: height,
            color: "#666",
            start: start,
            allowPageScroll: true
        };
        if (vis) {
            opt.alwaysVisible = true;
            opt.disabledFadeOut = true;
        }
        $el.slimScroll(opt);
    });


}


// Change check and radio buttons
function icheck(parent) {
    var $chkBox = $(parent).find('input:checkbox');
    if ($chkBox.length && $.fn.iCheck) {
        $chkBox.each(function () {
            // We verify if the checkbox is not a custom switch 
            if (!$(this).hasClass('switch')) {
                var icheck_style = $(this).data('style') ? $(this).data('style') : 'flat-blue';
                $(this).iCheck({
                    checkboxClass: 'icheckbox_' + icheck_style
                });
            }
        });

        /* Toggle All Checkbox Function */
        $('.toggle_checkbox').on('ifClicked', function () {
            var icheck_color = $(this).parent().data('color') ? '.icheckbox_flat-' + $(this).parent().data('color') : '.icheckbox_flat-blue';
            if ($(this).parent().hasClass('checked')) {
                $(this).closest('table').find('tr').removeClass('selected');
                $(this).closest('table').find(icheck_color).removeClass('checked');
                $(this).closest('table').find(':checkbox').attr('checked', false);
            } else {
                $(this).closest('table').find('tr').addClass('selected');
                $(this).closest('table').find(icheck_color).addClass('checked');
                $(this).closest('table').find(':checkbox').attr('checked', true);
            }
        });

        /* Toggle Select Class */
        $('.icheck').on('ifClicked', function () {
            if ($(this).parent().hasClass('checked')) {
                $(this).closest('tr').removeClass('selected');
                $(this).closest('tr').find(':checkbox').attr('checked', false);
            } else {
                $(this).parent().addClass('checked');
                $(this).closest('tr').addClass('selected');
                $(this).closest('tr').find(':checkbox').attr('checked', true);
            }
        });
    }

    /* de cubeplan
    if ($(parent).find(".icheck-me").length > 0) {
        $(parent).find(".icheck-me").each(function () {
            var $el = $(this);
            var skin = ($el.attr('data-skin') !== undefined) ? "_" + $el.attr('data-skin') : "",
			color = ($el.attr('data-color') !== undefined) ? "-" + $el.attr('data-color') : "";

            var opt = {
                checkboxClass: 'icheckbox' + skin + color,
                radioClass: 'iradio' + skin + color,
                increaseArea: "10%"
            }

            $el.iCheck(opt);
        });
    }*/
}

// Apply validation to all object
function applyValidate(parent) {

    if ($(parent).find('.form-validate').length > 0) {

        $(parent).find('.form-validate').each(function () {
            //var id = $(this).attr('id');
            //$("#" + id).validate({
            $(this).validate({
                errorElement: 'span',
                errorClass: 'help-block error',
                errorPlacement: function (error, element) {
                    //element.parent('.controls').append(error);
                    //element.closest("div").append(error);
                    element.parents('   .controls').append(error);
                    /*if (element.is(":radio")) {
                        error.insertBefore(element.parents('.radio-wrapper'));
                    } else if (element.is(":checkbox")) {
                        error.insertBefore(element.parent().children('input:first'));
                    } else if (element.is("textarea")) {
                        error.insertBefore(element);
                    } else {
                        error.appendTo(element.parent());
                    }*/
                },
                highlight: function (label) {
                    $(label).closest('.control-group').removeClass('error success').addClass('error');
                },
                success: function (label) {
                    label.addClass('valid').closest('.control-group').removeClass('error success').addClass('success');
                }
            });
        });
    }
}

//Translate text to current language
function translate(key) {
    if (__currentDictionary[key])
        return __currentDictionary[key];
    else
        return key;
}

function haveAccess(process) {
    if (__currentSession && __currentSession.userLogin == "super")
        return true
    return __processDictionary.hasOwnProperty(process);
}


function setLanguageDictionary(dic, appendToCurrent) {
    if (appendToCurrent) {
        __currentDictionary = $.extend({}, __currentDictionary, dic);
    }
    else {
        __currentDictionary = dic;
    }
}

function setProcessDictionary(process) {
    __processDictionary = new Object();
    for (var nn = 0; nn < process.length; nn++) {
        __processDictionary[process[nn]] = "";
    }
}

// format an date. Ej. dateString "2014-03-25T12:18:35.517", return "2014-03-25". TODO. view others formats (regional settngs??)
function formatDate(dateString) {
    if (dateString && dateString != "") {
        return dateString.substring(0, 10);
    }
    return "";
}

function escapeSingleQuote(text) {
    if (text)
        return text.replace(/'/g, "\\'");
}

function showMessage(type, message, title) {
    //if (!title)
    //    title = translate("warning") + "!";
    //$.gritter.add({
    //    title: title,
    //    text: message,
    //    image: null,
    //    sticky: true
    //});

    /**** INFO MESSAGE TYPE ****/
    if (type == 'info') {
        jNotify(
            message, {
                HorizontalPosition: "right",
                VerticalPosition: "bottom",
                ShowOverlay: false,
                TimeShown: 2000,
                OpacityOverlay: 0.5,
                MinWidth: 250
            });
    }
        /**** SUCCESS MESSAGE TYPE ****/
    else if (type == 'success') {
        jSuccess(
            message, {
                HorizontalPosition: "right",
                VerticalPosition: "bottom",
                ShowOverlay: false,
                TimeShown: 2000,
                OpacityOverlay: 0.5,
                MinWidth: 250
            });
    }
        /**** ERROR MESSAGE TYPE ****/
    else if (type == 'error') {
        jError(
            message, {
                HorizontalPosition: "right",
                VerticalPosition: "bottom",
                ShowOverlay: false,
                TimeShown: 2000,
                OpacityOverlay: 0.5,
                MinWidth: 250
            });
    }
}




$.fn.center = function () {
    return $(this).css({
        top: $(window).height() / 2 - $(this).height() / 2 + $(document).scrollTop(),
        left: $(window).width() / 2 - $(this).width() / 2 + $(document).scrollLeft()
    });
};